package by.dezhits.liltweets;

import oauth.signpost.OAuth;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import by.dezhits.liltweets.auth.TwitterAuthHelper;
import by.dezhits.liltweets.auth.TwitterCallback;
import by.dezhits.liltweets.auth.TwitterRecieveAccessTokenTask;
import by.dezhits.liltweets.auth.TwitterRecieveRequestTokenTask;

public class LoginActivity extends Activity {

	private WebView mWebView;
	
	private static final String ERROR_MESSAGE = "Error while authenticating";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void onSignInClick(View v) {
		v.setVisibility(View.GONE);
		final ProgressBar pb = (ProgressBar) findViewById(R.id.pb_login_activity);
		pb.setVisibility(View.VISIBLE);
		try {

			new TwitterRecieveRequestTokenTask()
					.execute(new TwitterCallback<String>() {
						@Override
						public void onError(){
							Toast.makeText(LoginActivity.this, ERROR_MESSAGE, Toast.LENGTH_LONG).show();
						}
						
						@Override
						public void onSuccess(String s) {
							pb.setVisibility(View.GONE);
							Button b = (Button) findViewById(R.id.sign_in_btn);
							b.setVisibility(View.INVISIBLE);
							mWebView = (WebView) findViewById(R.id.webView);
							mWebView.getSettings()
									.setJavaScriptCanOpenWindowsAutomatically(
											true);
							// mWebView.getSettings().setPluginsEnabled(true);
							mWebView.setWebViewClient(new WebViewClient() {
								@Override
								public boolean shouldOverrideUrlLoading(
										final WebView wv, String url) {
									if (url != null
											&& url.startsWith(TwitterAuthHelper.CALLBACK_URL)) {
										String v = Uri.parse(url)
												.getQueryParameter(
														OAuth.OAUTH_VERIFIER);
										new TwitterRecieveAccessTokenTask(v)
												.execute(new TwitterCallback<String[]>() {
													@Override
													public void onError(){
														Toast.makeText(LoginActivity.this, ERROR_MESSAGE, Toast.LENGTH_LONG).show();
													}
													
													@Override
													public void onSuccess(
															String[] s) {
														wv.setVisibility(View.INVISIBLE);
														SharedPreferences userDetails = getApplicationContext()
																.getSharedPreferences(
																		LoginActivity.this
																				.getString(R.string.user_details),
																		MODE_PRIVATE);
														Editor edit = userDetails
																.edit();
														String userId = s[0];
														String token = s[1];
														String tokenSecret = s[2];
														edit.putString(
																LoginActivity.this
																		.getString(R.string.user_id),
																userId);
														edit.putString(
																LoginActivity.this
																		.getString(R.string.token),
																token);
														edit.putString(
																LoginActivity.this
																		.getString(R.string.token_secret),
																tokenSecret);
														edit.putBoolean(
																LoginActivity.this
																		.getString(R.string.logged),
																true);
														edit.commit();
														Intent intent = new Intent(
																LoginActivity.this,
																FragmentsActivity.class);
														startActivity(intent);

														Account account = new Account(
																token,
																LoginActivity.this
																		.getString(R.string.account_type));

														Bundle params = new Bundle();
														params.putBoolean(
																ContentResolver.SYNC_EXTRAS_EXPEDITED,
																false);
														params.putBoolean(
																ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY,
																false);
														params.putBoolean(
																ContentResolver.SYNC_EXTRAS_MANUAL,
																false);
														ContentResolver
																.addPeriodicSync(
																		account,
																		LoginActivity.this
																				.getString(R.string.SYNC_ADAPTER_CONTENT_AUTHORITY),
																		params,
																		60);
														ContentResolver
																.setSyncAutomatically(
																		account,
																		LoginActivity.this
																				.getString(R.string.SYNC_ADAPTER_CONTENT_AUTHORITY),
																		true);

														AccountManager am = AccountManager
																.get(LoginActivity.this);
														boolean accountCreated = am
																.addAccountExplicitly(
																		account,
																		tokenSecret,
																		null);

														Bundle extras = LoginActivity.this
																.getIntent()
																.getExtras();
														if (accountCreated) {
															AccountAuthenticatorResponse response = extras
																	.getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
															Bundle result = new Bundle();
															result.putString(
																	AccountManager.KEY_ACCOUNT_NAME,
																	token);
															result.putString(
																	AccountManager.KEY_ACCOUNT_TYPE,
																	getString(R.string.account_type));
															response.onResult(result);

														}

														finish();

													}

												});

										return true;
									}
									return false;
								}
							});
							mWebView.loadUrl(s);
						}

					});

		} catch (Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}

	}

}
